<?php
header("Content-type:text/html; charset=utf-8;");
require '../../../ppf/fun.php';
require '../../../ppf/pdo_mysql.php';
require '../../../ppf/Filter.php';
/*p($_POST);
var_dump(json_decode($_POST['attachment']));
exit;*/
$pd=new pdo_mysql();
$filter=new Filter();
session_start();

if(empty($_SESSION['uid'])){
    $tips=array(
		'tips'=>'请登录后再进行操作',
		'url'=>'index.php'
	);
	$tips=urlencode(serialize($tips));
	header('Location:/tips.php?gets='.$tips);
	exit;
}

$submitMethod=$_SERVER["REQUEST_METHOD"];
if($submitMethod=='POST'){
    $subject         = empty($_POST['subject'])?0:Filter::safe_string($_POST['subject']);
	$receiver   = Filter::safe_string($_POST['receiver']);
	$content    = htmlspecialchars($_POST['content'],ENT_QUOTES);
	$sms_flag   = empty($_POST['sms_flag'])?0:Filter::filter_number($_POST['sms_flag']);
	$important   = empty($_POST['important'])?0:Filter::filter_number($_POST['important']);
	$attachment='';
    if($_POST['attachment']!=''){
    	$attachment_info=json_decode($_POST['attachment']);
		$attach=array();
    	foreach($attachment_info as $k=>$v){
			$attach[]=array('id'=>Filter::safe_string($v->id),'name'=>Filter::safe_string($v->name),'save_path'=>Filter::safe_string($v->save_path),'timestamp'=>time());
    		$attachment.=Filter::safe_string($v->id).',';
    	}
    }
	$attachment=rtrim($attachment,",");
	
	$in_data=array(
		'subject'    =>$subject,
		'sender'     =>$_SESSION['uid'],
		'receiver'   =>$receiver,
		'content'    =>$content,
		'attachment' =>$attachment,
		'sms_flag'   =>$sms_flag,
		'important'  =>$important,
		'timestamp'  =>time(),
		'read_flag'  =>0,
		'delete_flag'=>0,
		'send_flag'  =>0,//send_flag表示此记录是否为原纪录，如当有3个收件人时，除此记录外还会对每位收件人产生1条记录，这些记录的send_flag值为原纪录id号
	);
	
    if($pd->insert(array('data'=>$in_data,'table'=>'sys_email'))){
    	$last_insert_id=$pd->lastInsertId();
    	$re=explode(",", $receiver);
		$in_data2=$in_data;
    	foreach($re as $k=>$v){
    		$in_data2['receiver']=$v;
			$in_data2['send_flag']=$last_insert_id;
			$pd->insert(array('data'=>$in_data2,'table'=>'sys_email'));
    	}
		
		if(isset($attach)){
			foreach($attach as $k=>$v){
				$pd->insert(array('data'=>$v,'table'=>'sys_email_attachment'));
			}
		}
		$tips=array(
			'tips'=>'发送成功',
			'url' =>'/?t=email_sys'
		);
		$tips=urlencode(serialize($tips));
		//header('Location:../tips.php?gets='.$tips);
		echo("<script language='javascript'>window.parent.location.href='/tips.php?gets=".$tips."'</script>");
    }
}else{
	$tips=array(
		'tips'=>'不允许的表单提交方式，请按正常流程提交表单。',
		'url'=>'index.php'
	);
	$tips=urlencode(serialize($tips));
	echo("<script language='javascript'>window.parent.location.href='/tips.php?gets=".$tips."'</script>");
	//header('Location:../tips.php?gets='.$tips);
}
?>